package com.example.day03.lianxi.wordtext;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


/**
 * nc -lk 7777
 * hello world
 * hello java
 * hello spark
 *
 * return
 * (hello,2)
 * (java,1)
 * (hello,3)
 * (spark,1)
 */
public class Demo3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> stringDataStreamSource = env.socketTextStream("node3", 7777);

        stringDataStreamSource.flatMap((String s, Collector<Tuple2<String, Integer>> out) -> {
            String[] split = s.split(" ");
            for (String string : split) {
                out.collect(Tuple2.of(string, 1));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.INT)).keyBy(value -> value.f0).sum(1).print();

        // 执行 Flink 作业
        env.execute("Word Count Example");

    }
}
